import React, { useState, useEffect } from 'react';
import { apiService } from '../services/api';
import type { Statistics as StatsType } from '../types';

const Statistics: React.FC = () => {
  const [statistics, setStatistics] = useState<StatsType | null>(null);
  const [loading, setLoading] = useState(true);
  const [timeframe, setTimeframe] = useState<'week' | 'month' | 'year'>('week');

  useEffect(() => {
    const fetchStatistics = async () => {
      try {
        setLoading(true);
        const data = await apiService.getStatistics();
        setStatistics(data);
      } catch (error) {
        console.error('获取统计数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchStatistics();
  }, [timeframe]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (!statistics) {
    return (
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="text-center text-gray-500">
          <i className="fas fa-exclamation-triangle text-4xl mb-4"></i>
          <p>暂无统计数据</p>
        </div>
      </div>
    );
  }



  return (
    <div className="h-full w-full">
      <div className="space-y-6 pb-8 h-full">
        {/* 页面标题和时间筛选 */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">统计分析</h1>
          <p className="text-gray-600 mt-1">系统运营数据概览与分析</p>
        </div>
        <div className="flex space-x-2">
          {(['week', 'month', 'year'] as const).map((period) => (
            <button
              key={period}
              onClick={() => setTimeframe(period)}
              className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                timeframe === period
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
              }`}
            >
              {period === 'week' ? '本周' : period === 'month' ? '本月' : '本年'}
            </button>
          ))}
        </div>
      </div>

      {/* 核心指标卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div className="bg-gradient-to-r from-blue-500 to-blue-600 rounded-xl p-6 text-white">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-blue-100 text-sm font-medium">总工单数</p>
              <p className="text-3xl font-bold mt-1">{statistics.totalOrders}</p>
              <div className="flex items-center mt-2">
                <i className="fas fa-arrow-up text-xs"></i>
                <span className="text-xs ml-1">较上期 +12%</span>
              </div>
            </div>
            <div className="bg-blue-400 bg-opacity-30 rounded-full p-3">
              <i className="fas fa-clipboard-list text-2xl"></i>
            </div>
          </div>
        </div>

        <div className="bg-gradient-to-r from-green-500 to-green-600 rounded-xl p-6 text-white">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-green-100 text-sm font-medium">已完成</p>
              <p className="text-3xl font-bold mt-1">{statistics.statusDistribution?.completed || 0}</p>
              <div className="flex items-center mt-2">
                <i className="fas fa-arrow-up text-xs"></i>
                <span className="text-xs ml-1">较上期 +8%</span>
              </div>
            </div>
            <div className="bg-green-400 bg-opacity-30 rounded-full p-3">
              <i className="fas fa-check-circle text-2xl"></i>
            </div>
          </div>
        </div>

        <div className="bg-gradient-to-r from-yellow-500 to-yellow-600 rounded-xl p-6 text-white">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-yellow-100 text-sm font-medium">进行中</p>
              <p className="text-3xl font-bold mt-1">{statistics.statusDistribution?.processing || 0}</p>
              <div className="flex items-center mt-2">
                <i className="fas fa-arrow-down text-xs"></i>
                <span className="text-xs ml-1">较上期 -5%</span>
              </div>
            </div>
            <div className="bg-yellow-400 bg-opacity-30 rounded-full p-3">
              <i className="fas fa-cog text-2xl"></i>
            </div>
          </div>
        </div>

        <div className="bg-gradient-to-r from-purple-500 to-purple-600 rounded-xl p-6 text-white">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-purple-100 text-sm font-medium">待处理</p>
              <p className="text-3xl font-bold mt-1">{statistics.pendingOrders}</p>
              <div className="flex items-center mt-2">
                <i className="fas fa-arrow-up text-xs"></i>
                <span className="text-xs ml-1">较上期 +3%</span>
              </div>
            </div>
            <div className="bg-purple-400 bg-opacity-30 rounded-full p-3">
              <i className="fas fa-hourglass-half text-2xl"></i>
            </div>
          </div>
        </div>
      </div>

      {/* 图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 工单状态分布 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">工单状态分布</h3>
          <div className="space-y-4">
            {[
              { status: 'pending', count: statistics.statusDistribution?.waiting || 0, label: '待处理' },
              { status: 'processing', count: statistics.statusDistribution?.processing || 0, label: '进行中' },
              { status: 'completed', count: statistics.statusDistribution?.completed || 0, label: '已完成' },
              { status: 'cancelled', count: statistics.statusDistribution?.cancelled || 0, label: '已取消' }
            ].map(({ status, count, label }) => {
              const percentage = Math.round((count / statistics.totalOrders) * 100);
              return (
                <div key={status} className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full border ${
                      status === 'pending' ? 'bg-yellow-100 text-yellow-800 border-yellow-200' :
                      status === 'processing' ? 'bg-blue-100 text-blue-800 border-blue-200' :
                      status === 'completed' ? 'bg-green-100 text-green-800 border-green-200' :
                      'bg-red-100 text-red-800 border-red-200'
                    }`}>
                      {label}
                    </span>
                    <span className="text-sm text-gray-600">{count} 个</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <div className="w-24 bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${percentage}%` }}
                      ></div>
                    </div>
                    <span className="text-sm font-medium text-gray-900 w-10">{percentage}%</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* 系统性能指标 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-6">系统性能指标</h3>
          <div className="space-y-6">
            <div className="bg-green-50 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center space-x-3">
                  <div className="w-3 h-3 rounded-full bg-green-500"></div>
                  <span className="text-sm font-medium text-gray-900">完成率</span>
                </div>
                <span className="text-lg font-bold text-green-600">{Math.round(statistics.completionRate || 0)}%</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className="bg-green-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${statistics.completionRate || 0}%` }}
                ></div>
              </div>
            </div>
            <div className="bg-yellow-50 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center space-x-3">
                  <div className="w-3 h-3 rounded-full bg-yellow-500"></div>
                  <span className="text-sm font-medium text-gray-900">平均评分</span>
                </div>
                <span className="text-lg font-bold text-yellow-600">{(statistics.averageRating || 0).toFixed(1)} 分</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className="bg-yellow-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${((statistics.averageRating || 0) / 5) * 100}%` }}
                ></div>
              </div>
            </div>
            <div className="bg-blue-50 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center space-x-3">
                  <div className="w-3 h-3 rounded-full bg-blue-500"></div>
                  <span className="text-sm font-medium text-gray-900">总工单</span>
                </div>
                <span className="text-lg font-bold text-blue-600">{statistics.totalOrders} 个</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${Math.min((statistics.totalOrders / 10) * 100, 100)}%` }}
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 维修员绩效和系统统计 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 维修员绩效排行 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-900">维修员绩效排行</h3>
            <i className="fas fa-medal text-yellow-500"></i>
          </div>
          <div className="space-y-3">
            {statistics?.topMaintainers && statistics.topMaintainers.length > 0 ? statistics.topMaintainers.slice(0, 5).map((maintainer, index) => (
              <div key={maintainer._id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white ${
                    index === 0 ? 'bg-yellow-500' : 
                    index === 1 ? 'bg-gray-400' : 
                    index === 2 ? 'bg-yellow-600' : 'bg-blue-500'
                  }`}>
                    {index + 1}
                  </div>
                  <div>
                    <p className="font-medium text-gray-900">{maintainer.name}</p>
                    <p className="text-xs text-gray-500">评分: {maintainer.rating?.toFixed(1) || '暂无'}</p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="font-semibold text-gray-900">{maintainer.completedOrders} 单</p>
                  <p className="text-xs text-green-600">优秀维修员</p>
                </div>
              </div>
            )) : (
              <div className="text-center py-8 text-gray-500">
                <i className="fas fa-users text-4xl mb-4"></i>
                <p>暂无维修员数据</p>
              </div>
            )}
          </div>
        </div>

        {/* 系统统计信息 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">系统统计信息</h3>
          <div className="grid grid-cols-2 gap-4">
            <div className="text-center p-4 bg-blue-50 rounded-lg">
              <i className="fas fa-users text-2xl text-blue-600 mb-2"></i>
              <p className="text-2xl font-bold text-gray-900">{statistics.totalUsers}</p>
              <p className="text-sm text-gray-600">总用户数</p>
            </div>
            <div className="text-center p-4 bg-green-50 rounded-lg">
              <i className="fas fa-tools text-2xl text-green-600 mb-2"></i>
              <p className="text-2xl font-bold text-gray-900">{statistics.totalMaintainers}</p>
              <p className="text-sm text-gray-600">维修员数</p>
            </div>
            <div className="text-center p-4 bg-purple-50 rounded-lg">
              <i className="fas fa-clock text-2xl text-purple-600 mb-2"></i>
              <p className="text-2xl font-bold text-gray-900">2.5 天</p>
              <p className="text-sm text-gray-600">平均处理时间</p>
            </div>
            <div className="text-center p-4 bg-yellow-50 rounded-lg">
              <i className="fas fa-star text-2xl text-yellow-600 mb-2"></i>
              <p className="text-2xl font-bold text-gray-900">4.8</p>
              <p className="text-sm text-gray-600">平均评分</p>
            </div>
          </div>
        </div>
      </div>

      {/* 最近活动 */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-lg font-semibold text-gray-900">最近活动</h3>
          <i className="fas fa-history text-gray-400"></i>
        </div>
        <div className="flow-root">
          <ul className="space-y-4">
            <li className="flex items-center space-x-4 p-3 bg-green-50 rounded-lg">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-green-500 flex-shrink-0">
                <i className="fas fa-check text-white text-xs"></i>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm text-gray-500">
                  工单 <span className="font-medium text-gray-900">#12345</span> 已完成
                </p>
              </div>
              <div className="text-right text-sm text-gray-500 flex-shrink-0">
                <time>2分钟前</time>
              </div>
            </li>
            <li className="flex items-center space-x-4 p-3 bg-blue-50 rounded-lg">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-500 flex-shrink-0">
                <i className="fas fa-user-plus text-white text-xs"></i>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm text-gray-500">
                  新维修员 <span className="font-medium text-gray-900">张三</span> 加入系统
                </p>
              </div>
              <div className="text-right text-sm text-gray-500 flex-shrink-0">
                <time>10分钟前</time>
              </div>
            </li>
            <li className="flex items-center space-x-4 p-3 bg-yellow-50 rounded-lg">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-yellow-500 flex-shrink-0">
                <i className="fas fa-exclamation text-white text-xs"></i>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm text-gray-500">
                  紧急工单 <span className="font-medium text-gray-900">#12346</span> 需要处理
                </p>
              </div>
              <div className="text-right text-sm text-gray-500 flex-shrink-0">
                <time>15分钟前</time>
              </div>
            </li>
          </ul>
        </div>
      </div>
      </div>
    </div>
  );
};

export default Statistics;